package top.bluesword.laboratory.controller;

import jakarta.servlet.ServletException;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerRequest;
import org.springframework.web.servlet.function.ServerResponse;

import java.io.IOException;

/**
 * @author 李林峰
 */
@Controller
public class HandlerFunctionController {

    public HandlerFunctionController(GenericApplicationContext genericApplicationContext) {
        RouterFunction<ServerResponse> routerFunction = RouterFunctions.route()
            .GET("handler-function", this::get)
            .POST("handler-function", this::post)
            .build();
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(RouterFunction.class, () -> routerFunction).getBeanDefinition();
        genericApplicationContext.registerBeanDefinition("routerFunction",beanDefinition);
    }

    public ServerResponse get(ServerRequest request) {
        return ServerResponse.ok().body("你好，RouterFunction", ParameterizedTypeReference.forType(String.class));
    }

    private ServerResponse post(ServerRequest request) throws ServletException, IOException {
        String body = request.body(String.class);
        return ServerResponse.ok().body(body, ParameterizedTypeReference.forType(String.class));
    }

}
